/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pck_tramitedocu.pck_springtiles.pck_escuchador;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import pck_tramitedocu.pck_src.pck_pojos.Cls_Trabajador;
import pck_tramitedocu.pck_src.pck_utiles.Cls_Parametros;
import pck_tramitedocu.pck_src.pck_utiles.cls_utilitarios;
import pck_tramitedocu.pck_src.pck_utiles.enums.TipoControllerServletEnum;

/**
 *
 * @author USUARIO
 */
public class TramitedocuFilter implements Filter {
    
    private static final boolean debug = true;
    private FilterConfig filterConfig = null;
    
    public TramitedocuFilter() {
    }    
    
    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("TramitedocuFilter:DoBeforeProcessing");
        }

    }    
    
    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("TramitedocuFilter:DoAfterProcessing");
        }
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
        if (debug) {
            log("TramitedocuFilter:doFilter()");
        }
        
        HttpServletRequest req = (HttpServletRequest) request;
        Cls_Trabajador trabajadorSession = (Cls_Trabajador) req.getSession().getAttribute(Cls_Parametros.Session_OBJETO_USUARIO);
	String strUri = req.getServletPath();
        
        if(trabajadorSession==null){
            for(TipoControllerServletEnum tipoControllerServletEnum: TipoControllerServletEnum.list){
                if(cls_utilitarios.areStringEquals(tipoControllerServletEnum.getValor(), strUri)){
                    StringBuilder sbJScript = new StringBuilder("location.href='"); 
                    sbJScript.append("login.htm").append("';");
			
                    PrintWriter out=response.getWriter();
		    out.println("<script langauage='javaScript'>");
		    out.println("closeSession();");
		    out.println("</script>");
                    return;
                }
            }
        }
        doBeforeProcessing(request, response);
        
        Throwable problem = null;
        try {
            chain.doFilter(request, response);
        } catch (Throwable t) {
            problem = t;
            Logger.getLogger(TramitedocuFilter.class.getName()).log(Level.SEVERE, null, t);
        }
        
        doAfterProcessing(request, response);
        if (problem != null) {
            if (problem instanceof ServletException) {
                throw (ServletException) problem;
            }
            if (problem instanceof IOException) {
                throw (IOException) problem;
            }
            sendProcessingError(problem, response);
        }
    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }
    
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
    
    public void destroy() {        
    }

    /**
     * Init method for this filter
     */
    public void init(FilterConfig filterConfig) {        
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            if (debug) {                
                log("TramitedocuFilter:Initializing filter");
            }
        }
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
        if (filterConfig == null) {
            return ("TramitedocuFilter()");
        }
        StringBuffer sb = new StringBuffer("TramitedocuFilter(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());
    }
    
    private void sendProcessingError(Throwable t, ServletResponse response) {
        String stackTrace = getStackTrace(t);        
        
        if (stackTrace != null && !stackTrace.equals("")) {
            try {
                response.setContentType("text/html");
                PrintStream ps = new PrintStream(response.getOutputStream());
                PrintWriter pw = new PrintWriter(ps);                
                pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

                // PENDING! Localize this for next official release
                pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");                
                pw.print(stackTrace);                
                pw.print("</pre></body>\n</html>"); //NOI18N
                pw.close();
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
                Logger.getLogger(TramitedocuFilter.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                PrintStream ps = new PrintStream(response.getOutputStream());
                t.printStackTrace(ps);
                ps.close();
                response.getOutputStream().close();
            } catch (Exception ex) {
                Logger.getLogger(TramitedocuFilter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public static String getStackTrace(Throwable t) {
        String stackTrace = null;
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch (Exception ex) {
            Logger.getLogger(TramitedocuFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return stackTrace;
    }
    
    public void log(String msg) {
        filterConfig.getServletContext().log(msg);        
    }
}
